package com.tadpole.music.view.fragment.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lixs.charts.BarChart.LBarChartView;
import com.tadpole.music.R;
import com.tadpole.music.adapter.base.BaseAdapter;
import com.tadpole.music.adapter.home.WeekAdapter;
import com.tadpole.music.adapter.me.V2DayAdapter;
import com.tadpole.music.adapter.me.WorkV2Adapter;
import com.tadpole.music.bean.home.ClockInBean;
import com.tadpole.music.bean.me.MoNiErrorBean;
import com.tadpole.music.bean.me.MoNiSearchBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.iView.me.MoNiSearchIView;
import com.tadpole.music.presenter.me.MoNiSearchPresenter;
import com.tadpole.music.utils.DateUtils;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.activity.me.MoNiErrorDetailActivity;
import com.tadpole.music.view.fragment.base.BaseFragment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 模拟训练
 * Created By 孙岩
 * on 2020/12/25
 */
public class MoNiV2Fragment extends BaseFragment implements MoNiSearchIView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private static final String ARG_PARAM4 = "param4";
    //数据源
    private MoNiErrorBean.DataBean mParam1;
    //学生id
    private String mParam2;
    //学生头像
    private String mParam3;
    //学生昵称
    private String mParam4;

    //做题总数
    private TextView tvOne;
    //做题总时长
    private TextView tvTwo;
    //错题总数
    private TextView tvThree;
    //正确率
    private TextView tvFour;
    //柱状图
    private LBarChartView frameNewBase;

    //时间
    private TextView tvDate;
    //上一月
    private View leftIcon;
    //下一月
    private View rightIcon;
    private RadioGroup radioGroup;
    private RadioButton mRadio21;
    private RadioButton mRadio22;
    private RadioButton mRadio23;
    private RadioButton mRadio24;
    //有数据
    private LinearLayout llHaveData;
    //总做题数
    private TextView tvOne1;
    //做题总时长
    private TextView tvTwo1;
    //总错题数
    private TextView tvThree1;
    //正确率
    private TextView tvFour1;

    //无数据
    private TextView tvNoData;

    //练习recyclerView
    private RecyclerView rvWork;
    //练习的adapter
    private WorkV2Adapter workV2Adapter;

    //星期数据
    private List<String> weekList;
    //星期recyclerView
    private RecyclerView rvWeek;
    //星期adapter
    private WeekAdapter weekAdapter;

    //天recyclerView
    private RecyclerView rvDay;
    //天adapter
    private V2DayAdapter dayAdapter;
    //天数的数据
    private List<ClockInBean> dayList;

    //当前为0 向左为负数 向右为正数
    private int position = 0;

    //筛选以后的数据
    private MoNiSearchPresenter moNiSearchPresenter;

    public static MoNiV2Fragment newInstance(MoNiErrorBean.DataBean param1, String param2,String param3,String param4) {
        MoNiV2Fragment fragment = new MoNiV2Fragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, param3);
        args.putString(ARG_PARAM4, param4);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_moni_v2;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mParam1 = (MoNiErrorBean.DataBean) getArguments().getSerializable(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mParam3 = getArguments().getString(ARG_PARAM3);
            mParam4 = getArguments().getString(ARG_PARAM4);
        }
    }

    @Override
    protected void initView(View mRootView) {
        tvOne = mRootView.findViewById(R.id.tvOne);
        tvTwo = mRootView.findViewById(R.id.tvTwo);
        tvThree = mRootView.findViewById(R.id.tvThree);
        tvFour = mRootView.findViewById(R.id.tvFour);
        frameNewBase = mRootView.findViewById(R.id.frameNewBase);
        rvDay = mRootView.findViewById(R.id.rvDay);
        rvWeek = mRootView.findViewById(R.id.rvWeek);
        rvWork = mRootView.findViewById(R.id.rvWork);
        leftIcon = mRootView.findViewById(R.id.leftIcon);
        rightIcon = mRootView.findViewById(R.id.rightIcon);
        tvDate = mRootView.findViewById(R.id.tvDate);

        radioGroup = mRootView.findViewById(R.id.radioGroup);
        mRadio21 = mRootView.findViewById(R.id.mRadio21);
        mRadio22 = mRootView.findViewById(R.id.mRadio22);
        mRadio23 = mRootView.findViewById(R.id.mRadio23);
        mRadio24 = mRootView.findViewById(R.id.mRadio24);
        llHaveData = mRootView.findViewById(R.id.llHaveData);
        tvOne1 = mRootView.findViewById(R.id.tvOne1);
        tvTwo1 = mRootView.findViewById(R.id.tvTwo1);
        tvThree1 = mRootView.findViewById(R.id.tvThree1);
        tvFour1 = mRootView.findViewById(R.id.tvFour1);
        tvNoData = mRootView.findViewById(R.id.tvNoData);

        initNewBarDatas();
        initData();
        initListeners();

        moNiSearchPresenter = new MoNiSearchPresenter();
        moNiSearchPresenter.attachView(this);

    }


    @SuppressLint("SetTextI18n")
    private void initNewBarDatas() {
        //总体统计
        tvOne.setText("做题总数" + mParam1.getTotal().getTotal_questions() + "题");
        tvTwo.setText("做题总时长" + mParam1.getTotal().getTotal_time() + "分钟");
        tvThree.setText("错题总数" + mParam1.getTotal().getTotal_err_no() + "道");

        //返回0.58 *100 的精度问题
        BigDecimal bigDecimal = new BigDecimal(mParam1.getTotal().getRate());
        String a = bigDecimal.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString();
        tvFour.setText("正确率" + a + "%");


        final List<Double> datas = new ArrayList<>();
        final List<String> description = new ArrayList<>();

        datas.add(Double.parseDouble(mParam1.getTotal().getTotal_questions() + ""));
        datas.add(Double.parseDouble(mParam1.getTotal().getTotal_time() + ""));
        datas.add(Double.parseDouble(mParam1.getTotal().getTotal_err_no() + ""));

        String x = ((Double.parseDouble(mParam1.getTotal().getRate())) * mParam1.getTotal().getTotal_questions()) + "";
        datas.add(Double.parseDouble(x));


        description.add("总题数(道)");
        description.add("总时长(分钟)");
        description.add("错题总数(道)");
        description.add("正确数(道)");


        frameNewBase.setDatas(datas, description, true);
    }

    //初始化数据
    @SuppressLint("SetTextI18n")
    private void initData() {
        //星期数据
        tvDate.setText(DateUtils.getCurrentYearAndMonth());
        //星期数据
        weekList = new ArrayList<>();
        weekList.add("日");
        weekList.add("一");
        weekList.add("二");
        weekList.add("三");
        weekList.add("四");
        weekList.add("五");
        weekList.add("六");

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
        rvWeek.setLayoutManager(layoutManager);
        //创建适配器
        weekAdapter = new WeekAdapter(getActivity(), weekList);
        //给RecyclerView设置适配器
        rvWeek.setAdapter(weekAdapter);
        rvWeek.setFocusable(false);

        //第一次进来初始化日历的数据
        initRiLiData(mParam1);
        //第一次进来初始化的底部和导航数据
        initWorks(mParam1);
    }

    private void initListeners() {
        //当日统计
        mRadio21.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else{
                        try{
                            mRadio21.setChecked(true);
                            String startDayTime = DateUtils.getStartDayTime(position,DateUtils.getDay());
                            String endDayTime = DateUtils.getEndDayTime(position,DateUtils.getDay());
                            moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),startDayTime,endDayTime,3);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }else{
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });

        //本周统计
        mRadio22.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else{
                        mRadio22.setChecked(true);
                        String startWeekTime = DateUtils.getWeekStart();
                        String endWeekTime = DateUtils.getWeekEnd();
                        moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),startWeekTime,endWeekTime,3);
                    }
                }else{
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }

            }
        });

        //本月统计
        mRadio23.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else{
                        try{
                            mRadio23.setChecked(true);
                            String startMonth = DateUtils.getStartTime(0);
                            String endMonth = DateUtils.getEndTime(0);
                            moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),startMonth,endMonth,3);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }else{
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }

            }
        });

        //全部统计
        mRadio24.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else{
                        mRadio24.setChecked(true);
                        moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),"2020-01-01 00:00:00",Mutils.getSystemTime(),3);
                    }
                }else{
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }

            }
        });

        //左按钮
        leftIcon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        try{
                            //每次向左则-1
                            position = position - 1;
                            moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),DateUtils.getStartTime(position),DateUtils.getEndTime(position),1);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            }
        });

        //右按钮
        rightIcon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        try{
                            //每次向右则+1
                            position = position + 1;
                            moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),DateUtils.getStartTime(position),DateUtils.getEndTime(position),1);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                } else {
                    ToastUtils.show(getResources().getString(R.string.net_work));
                }
            }
        });
    }

    //设置导航栏为都不选中
    private void setNavFalse(){
        radioGroup.clearCheck();
    }


    //筛选以后数据的回调
    @Override
    public void showMoNiSearch(MoNiErrorBean.DataBean dataBean,int flag) {
        if(flag==1){
            //导航
            setNavFalse();
            //筛选以后的日历
            initRiLiData(dataBean);
            //筛选以后的work
            initWorks(dataBean);
        }else if(flag==2){
            //导航
            setNavFalse();
            //筛选以后的work
            initWorks(dataBean);
        }else if(flag==3){
            //筛选以后的work
            initWorks(dataBean);
        }
    }

    //初始化work 和 统计数据
    @SuppressLint("SetTextI18n")
    private void initWorks(final MoNiErrorBean.DataBean bean){
        //练习数据
        GridLayoutManager layoutManager2 = new GridLayoutManager(getActivity(), 3);
        rvWork.setLayoutManager(layoutManager2);
        //创建适配器
        workV2Adapter = new WorkV2Adapter(getActivity(), bean);
        //给RecyclerView设置适配器
        rvWork.setAdapter(workV2Adapter);
        rvWork.setNestedScrollingEnabled(false);
        rvWork.setFocusable(false);

        workV2Adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(getActivity(), MoNiErrorDetailActivity.class);
                        intent.putExtra("user_id",Integer.parseInt(mParam2));
                        intent.putExtra("rank_id",bean.getRank_id());
                        intent.putExtra("title",bean.getMonth_class_static().get(position).getName());
                        intent.putExtra("class_id",bean.getMonth_class_static().get(position).getClass_id());
                        intent.putExtra("student_avatar",mParam3);
                        intent.putExtra("student_nickname",mParam4);
                        startActivity(intent);
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });


        if(bean.getMonth_data_static().getRate().equals("0.00")){
            llHaveData.setVisibility(View.GONE);
            tvNoData.setVisibility(View.VISIBLE);
        }else{
            llHaveData.setVisibility(View.VISIBLE);
            tvNoData.setVisibility(View.GONE);
            //筛选统计
            tvOne1.setText("做题总数" + bean.getMonth_data_static().getTotal_questions() + "题");
            tvTwo1.setText("做题总时长" + bean.getMonth_data_static().getTotal_time() + "分钟");
            tvThree1.setText("错题总数" + bean.getMonth_data_static().getTotal_err_no() + "道");

            //返回0.58 *100 的精度问题
            BigDecimal bigDecimal = new BigDecimal(bean.getMonth_data_static().getRate());
            String a = bigDecimal.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString();
            tvFour1.setText("正确率" + a + "%");
        }
    }

    //初始化日历 天的数据
    private void initRiLiData(MoNiErrorBean.DataBean dataBean) {
        //设置日期
        tvDate.setText(DateUtils.getLeftMonth(position));
        int leftMaxDay = DateUtils.getLeftMonthLastDay(position);
        //天数据
        dayList = new ArrayList<>();

        for (int i = 0; i < DateUtils.getWeek(position) - 1; i++) {
            //DateUtil.getFirstDayOfMonth()获取当月第一天是星期几，星期日是第一天，依次类推 0为空 false签到状态为false
            dayList.add(new ClockInBean(0, false,false));
        }

        for (int i = 0; i < leftMaxDay; i++) {
            dayList.add(new ClockInBean(i + 1, false));
        }

        for (int x = 0; x < dataBean.getMonth_data().getDays().size(); x++) {
            for (int a = 0; a < dayList.size(); a++) {
                if (dataBean.getMonth_data().getDays().get(x) == dayList.get(a).getDay()) {
                    dayList.get(a).setClock(true);
                }
            }
        }

        for(int i=0;i<dayList.size();i++){
            if(dayList.get(i).getDay()>DateUtils.getDay()){
                if(position==0){
                    dayList.get(i).setNext(true);
                }else{
                    dayList.get(i).setNext(false);
                }
            }
        }

        GridLayoutManager layoutManager1 = new GridLayoutManager(getActivity(), 7);
        rvDay.setLayoutManager(layoutManager1);
        //创建适配器
        dayAdapter = new V2DayAdapter(getActivity(), dayList,position);
        //给RecyclerView设置适配器
        rvDay.setAdapter(dayAdapter);
        rvDay.setNestedScrollingEnabled(false);
        rvDay.setFocusable(false);

        dayAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int p) {
                if (Mutils.isNetworkAvailable()) {
                    if (SpUtil.getInstance(getActivity()).getString(Constant.TOKEN, "").equals("")) {
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    } else {
                        try{
                            String startDayTime = DateUtils.getStartDayTime(position,dayList.get(p).getDay());
                            String endDayTime = DateUtils.getEndDayTime(position,dayList.get(p).getDay());
                            moNiSearchPresenter.getMoNiSearch(Integer.parseInt(mParam2),mParam1.getRank_id(),startDayTime,endDayTime,2);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }
}
